package com.dtw.ditouwang.ui.mine;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dtw.ditouwang.R;
import com.dtw.ditouwang.beans.CommonBean;
import com.dtw.ditouwang.beans.PersonBean;
import com.dtw.ditouwang.beans.SetUserHeadBackBean;
import com.dtw.ditouwang.beans.UserBean;
import com.dtw.ditouwang.beans.UserSendCollectBean;
import com.dtw.ditouwang.models.WebApi;
import com.dtw.ditouwang.repositories.UserRepository;
import com.dtw.ditouwang.ui.BaseActivity;
import com.dtw.ditouwang.ui.OnItemClickListener;
import com.dtw.ditouwang.ui.PhotoPreviewActivity;
import com.dtw.ditouwang.ui.more.EditorChooseNormalDetailActivity;
import com.dtw.ditouwang.ui.more.EditorChoosePhotoAdapter;
import com.dtw.ditouwang.ui.more.EditorChoosePhotoDetailActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyCollectionActivity extends BaseActivity implements OnItemClickListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener {
    public final static String KeyUserID = "KeyUserID";
    private final int CodeCamera = 100, CodePicture = 101;
    MyCollectionAdapter myCollectionAdapter;
    List<UserSendCollectBean.DataBean> dataBeanList = new ArrayList<>();
    RadioButton send, collection;
    ImageView head, back;
    TextView name, address;
    AlertDialog alertDialog;
    PersonBean.DataBean.PersonInfoBean personInfoBean;

    public static void start(Context context, int userID) {
        Intent intent = new Intent(context, MyCollectionActivity.class);
        intent.putExtra(KeyUserID, userID);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_collection);
        final RecyclerView recyclerView = findViewById(R.id.recyclerview);
        send = findViewById(R.id.text_send);
        collection = findViewById(R.id.text_collection);
        head = findViewById(R.id.circleImageView);
        back = findViewById(R.id.image_user_back);
        name = findViewById(R.id.text_name);
        address = findViewById(R.id.text_address);
        send.setOnCheckedChangeListener(this);
        head.setOnClickListener(this);
        back.setOnClickListener(this);
        collection.setOnCheckedChangeListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        myCollectionAdapter = new MyCollectionAdapter(dataBeanList);
        myCollectionAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(myCollectionAdapter);
        getSeneCollect(1);

        webApi.getUserInfo(getIntent().getIntExtra(KeyUserID, 0)).enqueue(new Callback<PersonBean>() {
            @Override
            public void onResponse(Call<PersonBean> call, Response<PersonBean> response) {
                if (response.body().isResult()) {
                    personInfoBean = response.body().getData().getPerson_info();
                    name.setText(personInfoBean.getNickname());
                    address.setText(personInfoBean.getAddress());
                    if (personInfoBean.getHead_img() != null) {
                        Glide.with(head).load(WebApi.BaseUrl + personInfoBean.getHead_img().replace("\\", "/")).into(head);
                    }
                    if (personInfoBean.getBackground() != null) {
                        Glide.with(back).load(WebApi.BaseUrl + personInfoBean.getBackground().replace("\\", "/")).into(back);
                    }
                }
            }

            @Override
            public void onFailure(Call<PersonBean> call, Throwable t) {

            }
        });
    }

    private void getSeneCollect(int type) {
        webApi.getSendCollect(getIntent().getIntExtra(KeyUserID, 0), type).enqueue(new Callback<UserSendCollectBean>() {
            @Override
            public void onResponse(Call<UserSendCollectBean> call, Response<UserSendCollectBean> response) {
                if (response.body().isResult()) {
                    dataBeanList.clear();
                    dataBeanList.addAll(response.body().getData());
                    myCollectionAdapter.notifyDataSetChanged();
                } else {
                    dataBeanList.clear();
                    myCollectionAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<UserSendCollectBean> call, Throwable t) {

            }
        });
    }

    @Override
    public void onItemClick(int resID, int position, int state) {
        if (send.isChecked()) {
            Intent intent = new Intent(this, EditorChoosePhotoDetailActivity.class);
            intent.putExtra(EditorChoosePhotoDetailActivity.KeyID, dataBeanList.get(position).getActicle_id());
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, EditorChooseNormalDetailActivity.class);
            intent.putExtra(EditorChooseNormalDetailActivity.KeySYSID, dataBeanList.get(position).getId());
            startActivity(intent);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (b) {
            switch (compoundButton.getId()) {
                case R.id.text_send:
                    getSeneCollect(1);
                    break;
                case R.id.text_collection:
                    getSeneCollect(2);
                    break;
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CodeCamera:
                    Bitmap photo = (Bitmap) data.getExtras().get("data");
                    Glide.with(back).load(photo).into(back);
                    try {
                        File imgFile = new File(getExternalFilesDir(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));
                        photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadUserHead(imgFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CodePicture:
                    Uri selectedImage = data.getData();
                    Glide.with(back).load(selectedImage).into(back);
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                        File imgFile = new File(getExternalFilesDir(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadUserHead(imgFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    private void uploadUserHead(File imagefile) {
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imagefile);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("background", imagefile.getName(), requestFile);

        webApi.uploadBack(filePart).enqueue(new Callback<CommonBean>() {
            @Override
            public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                if (response.body().isResult() && response.body().getData() != null) {
                    UserRepository.getInstance().getUserBean().getData().setBackground((String) response.body().getData());
                    webApi.setBack(UserRepository.getInstance().getUserID(), (String) response.body().getData()).enqueue(new Callback<CommonBean>() {
                        @Override
                        public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                            if (response.body().isResult()) {

                            }
                        }

                        @Override
                        public void onFailure(Call<CommonBean> call, Throwable t) {

                        }
                    });
                } else {
                    showToast(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<CommonBean> call, Throwable t) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.circleImageView:
                Intent img = new Intent(this, PhotoPreviewActivity.class);
                ArrayList<String> arrayList=new ArrayList<>();
                arrayList.add(personInfoBean.getHead_img());
                img.putStringArrayListExtra(PhotoPreviewActivity.KeyUrlList,arrayList);
                startActivity(img);
                break;
            case R.id.image_user_back:
                if (getIntent().getIntExtra(KeyUserID, 0) == UserRepository.getInstance().getUserID()) {
                    View dialog = LayoutInflater.from(this).inflate(R.layout.dialog_choose_image, null);
                    alertDialog = new AlertDialog.Builder(this, R.style.BottomDialog).setView(dialog).show();
                    Window window = alertDialog.getWindow();
                    window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    dialog.findViewById(R.id.text_camera).setOnClickListener(this);
                    dialog.findViewById(R.id.text_picture).setOnClickListener(this);
                    dialog.findViewById(R.id.text_cancle).setOnClickListener(this);
                }
                break;
            case R.id.text_camera:
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CodeCamera);
                alertDialog.dismiss();
                break;
            case R.id.text_picture:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, CodePicture);
                alertDialog.dismiss();
                break;
            case R.id.text_cancle:
                if (alertDialog != null && alertDialog.isShowing()) {
                    alertDialog.dismiss();
                }
                break;
        }
    }
}
